import { defineComponent } from "vue";

export type Component = ReturnType<typeof defineComponent>;
export interface HookInstance {
  replace?: Component;
  wrap?: Component | Component[];
  head?: Component | Component[];
  tail?: Component | Component[];
}

const getHooksMap = () => {
  if (import.meta.env.SSR) {
    return global.__hooks;
  } else {
    return window.__hooks;
  }
};
export const useInjectHooks = (name: string) => {
  const hooks = getHooksMap();
  return hooks.get(name);
};
export const registerHooks = (name: string, inst: HookInstance) => {
  const hooks = getHooksMap();
  if (!hooks.has(name)) {
    hooks.set(name, {
      wrap: [],
      head: [],
      tail: []
    });
  }
  const hook = hooks.get(name);
  if (!hook) {
    throw new Error("Hook not found: " + name);
  }
  if (inst.replace) {
    hook.replace = inst.replace;
  }
  if (inst.wrap) {
    if (Array.isArray(inst.wrap)) {
      hook.wrap = hook.wrap.concat(inst.wrap);
    } else {
      hook.wrap.push(inst.wrap);
    }
  }
  if (inst.head) {
    if (Array.isArray(inst.head)) {
      hook.head = hook.head.concat(inst.head);
    } else {
      hook.head.push(inst.head);
    }
  }
  if (inst.tail) {
    if (Array.isArray(inst.tail)) {
      hook.tail = hook.tail.concat(inst.tail);
    } else {
      hook.tail.push(inst.tail);
    }
  }
};
